import axios from 'axios'

// 购物车模块
const cartModule = {
  // 开启子模块的命名空间，防止不同模块下 名字冲突
  namespaced: true,
  state () {
    return {
      goodsList: []
    }
  },
  mutations: {
    fn () { },
    setGoodsList (state, list) {
      state.goodsList = list
    }
  },
  actions: {
    async asyncSetGoodsList (store) {
      const resp = await axios({ url: 'https://www.escook.cn/api/cart' })
      store.commit('setGoodsList', resp.data.list)
    }
  },
  getters: {
    allCount (state) {
      return state.goodsList.reduce((sum, obj) => {
        if (obj.goods_state) { // 选中商品才累加数量
          sum += obj.goods_count;
        }
        return sum;
      }, 0)
    },
    allPrice (state) {
      return state.goodsList.reduce((sum, obj) => {
        if (obj.goods_state) {
          sum += obj.goods_count * obj.goods_price
        }
        return sum;
      }, 0)
    }
  }
}



export default cartModule